<?php

namespace backend\controllers;

use common\models\ExhibitionHall;
use common\models\ExhibitionMeeting;
use common\models\ExhibitionPicture;
use common\models\Region;
use common\services\ExhibitionAudienceServices;
use common\services\ExhibitionBusinessServices;
use common\services\ExhibitionMeetingServices;
use common\services\ExhibitionExhibitorServices;
use common\services\ExhibitionPictureServices;
use common\services\ExhibitionServices;
use common\services\ExhibitorServices;
use Yii;
use common\models\Exhibition;
use yii\data\ActiveDataProvider;
use backend\base\BaseBackController;
use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;

/**
 * ExhibitionController implements the CRUD actions for Exhibition model.
 */
class ExhibitionController extends BaseBackController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    //'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Exhibition models.
     * @return mixed
     */
    public function actionIndex()
    {
        $params = Yii::$app->request->queryParams;
        $params['defaultPageSize'] = $this->defaultPageSize;
        $service = new ExhibitionServices();
        $result = $service->search($params);

        return $this->render('index', [
            'dataProvider' => $result,
            'params' => $params,
        ]);
    }

    /**
     * Displays a single Exhibition model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Exhibition model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Exhibition();
        $meeting = new ExhibitionMeeting();
        $exhibitionExhibitorService = new ExhibitionExhibitorServices();

        $data = Yii::$app->request->post();
        if ($model->load($data) && $model->save()) {
            //更新信息
            $hall = ExhibitionHall::findOne($model->hall_id);
            $update = Exhibition::findOne($model->id);
            $update->hall_title = $hall->title;
            $region = Region::getRegionName($hall->region_id);
            $update->city = $region;
            $update->starttime = strtotime($model->starttime);
            $update->endtime = strtotime($model->endtime);
            $update->save();
            //展商数据构成保存
            $businessService = new ExhibitionBusinessServices();
            $businessService->saveBusinessData($model->id, Yii::$app->request->post('business_input'));
            //观众数据构成保存
            $audienceService = new ExhibitionAudienceServices();
            $audienceService->saveAudienceData($model->id, Yii::$app->request->post('audience_input'));
            //同期会议
            if ($meeting->load($data)) {
                $meeting->save();
            }
            //知名展商
            $exhibitor = isset($data['ExhibitionExhibitor']['exhibitor_id']) ? $data['ExhibitionExhibitor']['exhibitor_id'] : null;
            if (!empty($exhibitor)) {
                $exhibitionExhibitorService->saveExhibitorData($model->id, $exhibitor);
            }
            //图片
            if (!empty($data['picture'])) {
                $exhibitionPictureService = new ExhibitionPictureServices();
                $exhibitionPictureService->setExhibitionPicture($model->id, $data['picture']);
            }

            return $this->redirect(['view', 'id' => $model->id]);
        } else {

            if (Yii::$app->request->isPost && !empty($model->errors)) {
                Yii::$app->getSession()->setFlash('error', $model->firstErrors);
            }

            $business = [];
            $audience = [];
            $exhibitorService = new ExhibitorServices();
            $exhibitorAvaliable = $exhibitorService->getExhibitors();
            if (!empty($exhibitorAvaliable)) {
                $exhibitorAvaliable = ArrayHelper::map($exhibitorAvaliable, 'id', 'name');
            }
            if (!empty($model->starttime) && Yii::$app->request->isPost) $model->starttime = strtotime($model->starttime);
            if (!empty($model->endtime) && Yii::$app->request->isPost) $model->endtime = strtotime($model->endtime);
            $exhibitorAssigned = [];
            return $this->render('create', [
                'model' => $model,
                'business' => $business,
                'audience' => $audience,
                'meeting' => $meeting,
                'exhibitorAvaliable' => $exhibitorAvaliable,
                'exhibitorAssigned' => $exhibitorAssigned,
                'picture' => [],
            ]);
        }
    }

    /**
     * Updates an existing Exhibition model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $businessService = new ExhibitionBusinessServices();
        $audienceService = new ExhibitionAudienceServices();
        $meetingService = new ExhibitionMeetingServices();
        $meeting = $meetingService->getExhibitionMeeting($model->id);
        $exhibitionExhibitorService = new ExhibitionExhibitorServices();
        $exhibitionPictureService = new ExhibitionPictureServices();

        $data = Yii::$app->request->post();
        if ($model->load($data) && $model->save()) {
            //更新信息
            $hall = ExhibitionHall::findOne($model->hall_id);
            $update = Exhibition::findOne($model->id);
            $update->hall_title = $hall->title;
            $region = Region::getRegionName($hall->region_id);
            $update->city = $region;
            $update->starttime = strtotime($model->starttime);
            $update->endtime = strtotime($model->endtime);
            $update->save();
            //展商数据构成保存
            $businessService->saveBusinessData($model->id, Yii::$app->request->post('business_input'));
            $audienceService->saveAudienceData($model->id, Yii::$app->request->post('audience_input'));
            //同期会议
            $meeting->exhibition_id = $model->id;
            if ($meeting->load($data)) {
                $meeting->save();
            }
            //知名展商
            $exhibitor = isset($data['exhibitor_id']) ? $data['exhibitor_id'] : null;
            if (!empty($exhibitor)) {
                $exhibitionExhibitorService->saveExhibitorData($model->id, $exhibitor);
            }
            if (!empty($data['picture'])) {
                //图片
                $exhibitionPictureService->setExhibitionPicture($model->id, $data['picture']);
            }

            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            $business = $businessService->getExhibitionBusiness($model->id);
            $audience = $audienceService->getExhibitionAudience($model->id);
            $exhibitorService = new ExhibitorServices();

            $exhibitorAssigned = $exhibitionExhibitorService->getExhibitorsByExhibitionId($model->id);
            $exhibitor_id = array();
            if (!empty($exhibitorAssigned)) {
                $exhibitorAssigned = ArrayHelper::map($exhibitorAssigned, 'exhibitor_id', 'name');
                $exhibitor_id = array_keys($exhibitorAssigned);
            }
            $params = array(
                'not_in' => $exhibitor_id,
            );
            $exhibitorAvaliable = $exhibitorService->getExhibitors($params);
            if (!empty($exhibitorAvaliable)) {
                $exhibitorAvaliable = ArrayHelper::map($exhibitorAvaliable, 'id', 'name');
            }
            $picture = $exhibitionPictureService->getExhibitionPictureByEid($model->id);

            if (Yii::$app->request->isPost && !empty($model->errors)) {
                Yii::$app->getSession()->setFlash('error', $model->firstErrors);
            }

            if (!empty($model->starttime) && Yii::$app->request->isPost) $model->starttime = strtotime($model->starttime);
            if (!empty($model->endtime) && Yii::$app->request->isPost) $model->endtime = strtotime($model->endtime);

            return $this->render('update', [
                'model' => $model,
                'business' => $business,
                'audience' => $audience,
                'meeting' => $meeting,
                'exhibitorAvaliable' => $exhibitorAvaliable,
                'exhibitorAssigned' => $exhibitorAssigned,
                'picture' => $picture,
            ]);
        }
    }

    /**
     * Deletes an existing Exhibition model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Exhibition model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Exhibition the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Exhibition::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * @return array|Response
     */
    public function actionBatchDelete()
    {
        if (isset($_POST['datalist']) && Yii::$app->request->isPost) {
            $keys = $_POST['datalist'];
            Yii::$app->response->format = Response::FORMAT_JSON;
            try {
                Exhibition::deleteAllByKid($keys);
                return ['result'=>'success'];
            }
            catch (\Exception $ex)
            {
                return ['result'=>'failure', 'message' => $ex->getMessage()];
            }
        }
        else
        {
            return $this->redirect(['index']);
        }
    }

    /**
     * @return array|Response
     */
    public function actionBatchUpdateOrder()
    {
        if (isset($_POST['orders']) && Yii::$app->request->isPost) {
            $orders = $_POST['orders'];
            Yii::$app->response->format = Response::FORMAT_JSON;
            try {
                foreach ($orders as $key => $val){
                    $model = Exhibition::findOne($key);
                    $model->order = $val;
                    $model->update();
                }
                return ['result' => 'success'];
            }
            catch (\Exception $ex)
            {
                return ['result'=>'failure'];
            }
        }
        else
        {
            return $this->redirect(['index']);
        }
    }

    public function actionStatus($id, $status)
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        if ( Yii::$app->request->isPost) {
            $model = Exhibition::findOne($id);
            $model->status = $status;
            $model->save();
            return ['result' => 'success'];
        }
        else
        {
            return ['result' => 'failure'];
        }
    }

    /**
     * 展商构成
     * @param string $exhibitionId
     * @return string
     */
    public function actionGetBusiness($exhibitionId = ''){

        return $this->renderAjax('business', [

        ]);
    }

    /**
     * 观众构成
     * @param string $exhibitionId
     * @return string
     */
    public function actionGetAudience($exhibitionId = ''){

        return $this->renderAjax('audience', [

        ]);
    }

    /**
     * 导入
     * @return string
     */
    public function actionImport(){
        if (Yii::$app->request->isPost) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            $fileUrl = Yii::$app->request->post('fileUrl');
            if (empty($fileUrl)) {
                return ['code' => -1, 'data' => [], 'msg' => '请选择要导入的文件'];
            }
            $service = new ExhibitionServices();
            $errMsg = '';
            $result = $service->importData($fileUrl, $errMsg);
            if ($result > 0 ) {
                return ['code' => 0, 'data' => [], 'msg' => '成功添加'.$result.'条数据'];
            }else{
                if ($result == -1) {
                    $msg = '文件不存在';
                }elseif ($result == -2) {
                    $msg = '文件读取失败';
                }elseif ($result == -3) {
                    $msg = '未读取到有效数据';
                }else{
                    $msg = '成功添加 0 条数据';
                }
                return ['code' => -1, 'data' => [], 'msg' => $msg, 'errmsg' => $errMsg];
            }
        }

        return $this->renderAjax('import', [

        ]);
    }

}
